<?php


namespace App\Http\Requests\Manage\Product\Index;


use App\Models\HsCode;
use App\Models\Positive;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class RecordRequest extends FormRequest
{
    /**
     * 模板要素上传验证
     * @param $hsCode
     * @return array
     */
    public function rules(): array
    {
        $hsCode = HsCode::query()->where('code', '=', $this->input('hs_code'))->first();

        return [
            'name' => ['required', 'string', 'max:255'],

            'element' => ['required', 'max:255', function ($attribute, $value, $fail) use ($hsCode) {
                $el = count(explode('|', $value));
                if ($el - count($hsCode->element) !== 0) {
                    return $fail("请对比一下申报要素");
                }
            }],

            'hs_code' => ['required', 'size:10', Rule::exists('hs_codes', 'code'), function ($attribute, $value, $fail) {
                $count = Positive::query()
                    ->where('code', "=", substr($value, 0, 8))
                    ->count();
                if ($count === 0) {
                    return $fail('正面清单不存在!');
                }
            }],

            'country' => ['required', 'size:3', Rule::exists('country', 'code')],
            'unit' => ['required', 'size:3', Rule::exists('unit', 'code')],
            'net_weight' => ['required', 'numeric'],
            'qy1' => ['required', 'numeric', function ($attribute, $value, $fail) use ($hsCode) {
                if($hsCode->getAttribute('unit1') === '035'){
                    if($value !== $this->input('net_weight')){
                        return $fail('法定第一数量不等于净重!');
                    }
                }
            }],

            'qy2' => [Rule::requiredIf(function () use ($hsCode) {
                return !empty($hsCode->getAttribute('unit2'));
            }), 'numeric', function ($attribute, $value, $fail) use ($hsCode) {
                if($hsCode->getAttribute('unit2') === '035'){
                    if($value !== $this->input('net_weight')){
                        return $fail('法定第二数量不等于净重!');
                    }
                }
            }],
        ];
    }
}
